package com.phrp.service.impl;

import com.phrp.dao.HouseDao;
import com.phrp.entity.House;
import com.phrp.entity.vo.HouseSearchDataVo;
import com.phrp.entity.vo.PageData;
import com.phrp.exception.CustomizationException;
import com.phrp.service.HouseService;
import com.phrp.util.returnResult.ResponseResult;
import com.phrp.util.returnResult.ReturnInfoEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ssc
 * @since 2024-04-06
 */
@Service
public class HouseserviceImpl extends ServiceImpl<HouseDao, House> implements HouseService {

    @Autowired
    private HouseDao houseDao;

    /**
     * 获取房源信息
     *
     * @return
     */
    @Override
    public ResponseResult getHouseSource(PageData pageData) {
        // 分页参数，第一个为页码，第二个为分页条数
        Page<House> rowPage = new Page<>(pageData.getCurrentPage(), pageData.getPageSize());

        // 构建查询条件
        QueryWrapper<House> houseQueryWrapper = new QueryWrapper<>();
        houseQueryWrapper.select("h_uuid,name,area,picture,house_type,floor,detail_address,other_introduction,update_time,"
                + "dictionary_query('house', 'status', house.status) as status," +
                "dictionary_query('house', 'publish', house.publish) as publish");
        houseQueryWrapper.orderByDesc("update_time");

        // 查询
        Page<House> housePage = houseDao.selectPage(rowPage, houseQueryWrapper);

        // 将有用信息保存到数据中
        pageData.setTotalNumber(housePage.getTotal());
        pageData.setData(housePage.getRecords());

        return new ResponseResult<>(ReturnInfoEnum.SUCCESS, pageData);
    }

    /**
     * 删除房源信息
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = CustomizationException.class)
    @Override
    public ResponseResult deleteHouse(LinkedList<String> ids) {
        int i = houseDao.deleteBatchIds(ids);
        if (i <= 0) {
            // 数据库删除操作失效
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }
        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 修改房屋信息
     * @param house
     * @return
     */
    @Override
    public ResponseResult editHouse(House house) {
        UpdateWrapper<House> update = new UpdateWrapper();
        // 注：如果<>中不写House使用.set就会报错
        update.eq("h_uuid",house.getHUuid())
                .set("name",house.getName())
                .set("house_type",house.getHouseType())
                .set("floor",house.getFloor())
                .set("area",house.getArea())
                .set("detail_address",house.getDetailAddress())
                .set("picture",house.getPicture())
                .set("other_introduction",house.getOtherIntroduction())
                .set("update_time",LocalDateTime.now());//获取当前时间

        int i = houseDao.update(null, update);

        if(i != 1){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 更新发布状态
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updatePublish(String id, String type) {
        String[] ids = id.split(",");
        int i = houseDao.updateBatchByIds(ids,type);
        if(i != ids.length){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }
        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 更新状态
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(String id, String type) {
        UpdateWrapper<House> update = new UpdateWrapper<>();
        update.eq("h_uuid",id)
                .set("status",type);

        int i = houseDao.update(null, update);

        if(i != 1){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 新增房源信息
     * @param house
     * @return
     */
    @Override
    public ResponseResult AddHouse(House house) {
        // 修改time和uuid
        house.setHUuid(UUID.randomUUID().toString().replace("-", ""));
        house.setCreateTime(LocalDateTime.now());
        house.setUpdateTime(LocalDateTime.now());
        // 插入数据
        int insert = houseDao.insert(house);
        if(insert != 1 ){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }
        return new ResponseResult<>(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 条件搜索
     * @param searchData
     * @return
     */
    @Override
    public ResponseResult searchHouse(HouseSearchDataVo searchData) {
        searchData.setStartPage((searchData.getCurrentPage()-1)*searchData.getPageSize());
        LinkedList<House> list = houseDao.selectSearchPage(searchData);
        Integer totalCount = houseDao.selectTotalCount(searchData);

        PageData<List<House>> housePageData = new PageData<>();
        housePageData.setData(list);
        housePageData.setTotalNumber(totalCount);

        return new ResponseResult(ReturnInfoEnum.SUCCESS,housePageData);
    }

    /**
     * 获取巡查房源数据
     * @param houseSearch
     * @return
     */
    @Override
    public ResponseResult inspectionSearch(HouseSearchDataVo houseSearch) {
        houseSearch.setStartPage((houseSearch.getCurrentPage()-1)*houseSearch.getPageSize());
        LinkedList<House> houseData = houseDao.selectInspectionHouseData(houseSearch);
        Integer total = houseDao.getInspectionTotalNum(houseSearch);

        PageData<LinkedList<House>> pageData = new PageData<>();
        pageData.setTotalNumber(total);
        pageData.setData(houseData);

        return new ResponseResult(ReturnInfoEnum.SUCCESS,pageData);
    }
}
